package ivo.util;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class XmlUtil {
	private static StringBuilder resultXML = new StringBuilder("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
	/**
	 * 特殊字符转换 spacialChars为特殊字符， validChars为将要转换的字符。这两个数组是一一对应的
	 */
	private static String[] spacialChars = { "\n", "__","  "};
	private static String[] validChars = { "", "_",""};
	//将对象转换为XML
	public static String object2xml(Object inObj){
		XStream xStream = new XStream(new DomDriver());
		xStream.alias("transaction", inObj.getClass());
		xStream.autodetectAnnotations(true);
		String xml = resultXML.toString() + replaceSpecialChar(xStream.toXML(inObj));
		return xml;
	}

	//将XML转化为对象
	public static Object xml2object(String xml,Object inObj){
		Object objIn = new Object();
		XStream xstream = new XStream(new DomDriver());
		xstream.alias("transaction", inObj.getClass());
		xstream.processAnnotations(inObj.getClass());
		objIn = xstream.fromXML(xml);
		return objIn;
	}
	
	/**
	 * 转换特殊字符
	 * @param s
	 * @return
	 */
	private static String replaceSpecialChar(String s) {
		for (int i = 0; i < spacialChars.length; i++) {
			s = s.replaceAll(spacialChars[i], validChars[i]);
		}
		return s;
	}
}
